/**
 * Created by zhouli on 2019/2/27
 * ie9上传附件
 */
import React from 'react';
import config from 'config';
import {message} from 'antd';
import {messages} from "share/common";
import FileUpload from 'components/template/ie-file-upload/file-upload';
import "styles/components/template/ie-file-upload/ie-file-upload.scss";
import excelImage from 'images/file-type/excel.png'
import pdfImage from 'images/file-type/pdf.png'
import pptImage from 'images/file-type/ppt.png'
import txtImage from 'images/file-type/txt.png'
import wordImage from 'images/file-type/word.png'
import unknownImage from 'images/file-type/unknown.png'
import constants from 'share/constants';
import configureStore from 'stores';

class IeFileUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList: [],
      result: [],
      previewIndex: 0, //预览图片的index
      imgIsUploading: false //图片是否是正在上传的状态，用来解决 isShowDefault 为true时，上传过程中会出现显示两张图片的情况
    }
  }

  componentDidMount() {
    if (this.props.defaultFileList.length) {
      this.showDefaultFileList(this.props.defaultFileList);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.defaultFileList.length !== this.props.defaultFileList.length) {
      this.showDefaultFileList(nextProps.defaultFileList);
    }
    if (nextProps.isShowDefault) {
      if (nextProps.defaultFileList.splice && !this.state.imgIsUploading) {
        this.showDefaultFileList(nextProps.defaultFileList);
      }
    }
  }

  //为了显示默认已经上传的图片
  showDefaultFileList = (defaultFileList) => {
    let fileList = [];
    defaultFileList.map(attachment => {
      fileList.push({
        uid: attachment.attachmentOID,
        name: attachment.fileName,
        url: attachment.fileURL
      })
    });
    this.setState({ fileList, result: defaultFileList })
  };
  //上传文件之前的检测，返回 false 不会上传
  beforeUpload = (file) => {
    for (let key in file) {
      console.log(key)
      console.log(file[key])
    }
    if (window.ISIE9) {
      //如果是 ie9 不校验
      return true;
    }
    if (this.props.fileType) {  //控制上传图片的类型
      let isFileType = false;
      this.props.fileType.map(type => {
        file.type === `image/${type}` && (isFileType = true)
      });
      if (!isFileType) {
        message.error(messages('components.key398'/*上传失败，图片格式错误*/));
        return false;
      }
    }
    if (this.props.fileSize) {  //控制上传图片的大小
      const isLtSize = file.size / 1024 / 1024 <= this.props.fileSize;
      if (!isLtSize) {
        message.error(messages('components.key656', {arg1: this.props.fileSize}/*上传失败，图片应不大于 {arg1} M*/));
        return false;
      }
    }
    this.setState({imgIsUploading: true});
    return true;
  }
  handleChange = (response) => {
    const { fileList, result } = this.state;
    fileList.push(response);
    result.push(response);
    this.setState({fileList, result, imgIsUploading: false}, () => {
      message.success(`${messages('components.key399'/*上传成功*/)}`);
      this.props.onChange(result);
      this.props.setResult(fileList, response);
    });
  };

  getImage = (file) => {
    let sections = (file.fileName || file.name).split('.');
    let extension = sections[sections.length - 1].toLowerCase();
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
    let wordExtension = ['doc', 'docx'];
    let pptExtension = ['ppt', 'pptx'];
    let excelExtension = ['xls', 'xlsx'];
    let txtExtension = ['txt'];
    let pdfExtension = ['pdf'];
    if (imageExtension.has(extension))
      return file.thumbnailUrl || file.fileURL || file.url;
    if (wordExtension.has(extension))
      return wordImage;
    if (pptExtension.has(extension))
      return pptImage;
    if (excelExtension.has(extension))
      return excelImage;
    if (txtExtension.has(extension))
      return txtImage;
    if (pdfExtension.has(extension))
      return pdfImage;
    return unknownImage;
  };
  deleteImage = (img) => {
    const { result, fileList } = this.state;
    let attachmentOid = img.attachmentOID || img.uid;
    result.map((item, index) => {
      if (item.attachmentOID === attachmentOid) {
        result.splice(index, 1);
        this.props.handleDelete(item.id);
      }
    });
    fileList.map((item, index) => {
      if (item.uid === attachmentOid || item.attachmentOID === attachmentOid) {
        fileList.splice(index, 1);
      }
    });
    this.setState({ result, fileList });
    this.props.onChange(result)
  }
  // 下载
  handleDownload = (file) => {
    console.log(file);
    console.log(file.response ? file.response.fileURL : file.fileURL);
    window.open(file.response ? file.response.fileURL : file.url ? file.url : file.fileURL, '_blank')
  };
  render() {
    const { disabled, fileSize } = this.props;
    const { fileList } = this.state;
    let token = this.props.token ? this.props.token : configureStore.store.getState().main.authToken.access_token;
    let data = this.props.data ? this.props.data : {attachmentType: this.props.attachmentType};
    return (
      <div className="ie-file-upload-wrap">
        {!disabled && (
          <FileUpload
            onChange={this.handleChange}
            token={token}
            data={data}
            multiple={this.props.multiple}
            beforeUpload={this.beforeUpload}
            disabled={disabled || fileList.length >= this.props.maxNum}
            uploadUrl={this.props.uploadUrl}
            accept={this.props.accept}
          />
        )}
        {
          this.props.showMaxNum && !disabled && (
            <div style={{marginTop: 10}}>({messages('common.max.upload.attachment', {max: this.props.maxNum})/*最多上传 {max} 个附件*/})</div>
          )
        }
        {
          !disabled && (
            <div>
              <div>{this.props.placeHolder}</div>
            </div>
          )
        }
        <div className="img-list-wrap">
          {fileList.length > 0 && fileList.map((img, index) => {
            return (
              <div className="img-item">
                <div className="img-item-wrap" onClick={()=>{this.handleDownload(img)}}>
                  <img key={index} src={this.getImage(img)}/>
                </div>
                {!disabled && (
                  <div className="img-item-text" onClick={() => {
                    this.deleteImage(img)
                  }}> {messages('common.delete')/*删除*/}</div>
                )}
              </div>
            )
          })}
          <div className="clear"/>
        </div>
      </div>
    );
  }
}

IeFileUpload.propTypes = {
  multiple: React.PropTypes.bool,  //是否多选
  uploadUrl: React.PropTypes.string,  //上传URL
  attachmentType: React.PropTypes.any,
  defaultFileList: React.PropTypes.array,  //默认上传的文件列表
  onChange: React.PropTypes.func,  //上传成功后的回调
  maxNum: React.PropTypes.number,  //最大上传文件的数量
  placeHolder: React.PropTypes.string,  //控件配置的提示文案
  token: React.PropTypes.any,
  fileType: React.PropTypes.array,  //上传文件的类型
  fileSize: React.PropTypes.number,  //上传文件的大小
  disabled: React.PropTypes.bool, //是否禁用
  showMaxNum: React.PropTypes.bool, //是否显示最多上传多少图片
  data: React.PropTypes.object, //上传接口的参数
  handleDelete: React.PropTypes.func, //删除附件的回调
  setResult: React.PropTypes.func, //上传接口返回结果保存
  accept: React.PropTypes.string,//附件只接受选择的类型
};
IeFileUpload.defaultProps = {
  multiple: false,
  uploadUrl: `${config.baseUrl}/api/upload/attachment/v2`,
  defaultFileList: [],
  onChange: () => {
  },
  handleDelete: () => {
    return true;
  },
  setResult: (result, response) => {
  },
  attachmentType: "INVOICE_IMAGES",
  maxNum: 9,
  placeHolder: '',
  disabled: false,
  showMaxNum: false,
  accept: constants.acceptFileTypes,
};

export default IeFileUpload;

